package com.feihong.txgw.ui.activity.setting;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.feihong.txgw.R;
import com.feihong.txgw.app.App;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.SystemMsgMessage;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.ui.activity.setting.webviewinterface.MessagelistWebviewInterFace;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.feihong.txgw.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;

/**
 * 2017.7.22
 * 消息界面
 * 张鹏
 */
public class MessageListActivity extends BaseActivity {

    @BindView(R.id.webviewframe)
    RelativeLayout webviewFrame;
    private AgentWeb mAgentWeb;
    @BindView(R.id.messagewListSwiperefreshlayout)
    SwipeRefreshLayout mswiperefreshlayout;

    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataBtn;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if(activityIsDestory()){
                return;
            }
            if (msg.what == 10) {
                loadPage();
            }else if(msg.what == 11){
                mConnectErrorLayout.setVisibility(View.VISIBLE);
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_messagelist;
    }

    private void refreshTokenRequest() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain();
                if(RefreshToken.getInstance().RetrofitRefreshTokenForGet()){
                    message.what = 10;
                }else {
                    message.what = 11;
                }
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        setBackButtonFinish();
        setPageTitle("系统消息");
        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectErrorLayout.setVisibility(View.GONE);
                refreshTokenRequest();
            }
        });

        //设置刷新时动画的颜色，可以设置4个
        mswiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mswiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        mswiperefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mswiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshTokenRequest();
            }
        });
        WebView4Scroll webView4Scroll = new WebView4Scroll(MessageListActivity.this, mswiperefreshlayout);
        webView4Scroll.setVerticalScrollBarEnabled(false);
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewFrame, new RelativeLayout.LayoutParams(-1, -1))//
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient).setWebView(webView4Scroll)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .createAgentWeb()
                .ready();
        //同步 Cookie
        //AgentWebConfig.syncCookies("http://www.djml.com","ID=XXXX")
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mswiperefreshlayout.setRefreshing(true);
//            }
//        },200);
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mswiperefreshlayout.setRefreshing(false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {


    };

    @Override
    public void bindData() {

        refreshTokenRequest();
    }

    private void loadPage() {
        String url = "";
        String params = new SignToken().setSigen(new HashMap<String, String>());
        url = HttpTools.MESSAGE_HOME + "?" + params;
        mAgentWeb = mPreAgentWeb.go(url);

        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        // 安卓调用js(传入js方法名)
        mAgentWeb.getJsAccessEntrace().quickCallJs("");

        // js调用安卓
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new MessagelistWebviewInterFace(mAgentWeb, this,
                new ActionCallBack() {
                    @Override
                    public void go_list() {
                        go_List();
                    }

                    @Override
                    public void kefu() {
                        keFu();
                    }

                }));
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    /*    跳转到消息列表    */
    private void go_List() {
        startActivity(new Intent(MessageListActivity.this, MessageContentActivity.class));
    }

    /*    跳转到客服    */
    private void keFu() {
        startActivity(new Intent(MessageListActivity.this, ServiceMessageActivity.class));
    }

    public interface ActionCallBack {
        public void go_list();

        public void kefu();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAgentWeb != null) {
            mAgentWeb.destroy();
        }
        if(mHandler != null && mHandler.getLooper() == Looper.getMainLooper()){
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshMsgList(SystemMsgMessage systemMsgMessage) {
        if (mAgentWeb != null) {
            mAgentWeb.getUrlLoader().reload();
        }
    }
}
